#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
责任链模式 (Chain of Responsibility Pattern) - Python实现详解

概述引导：
责任链模式为请求创建了一个接收者对象的链。这种模式给予请求的类型，
对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式。

学习要点：
1. 传统责任链实现
2. 函数式责任链
3. 装饰器责任链
4. 异步责任链
5. 中间件模式

Java对比要点：
- Java使用抽象类定义处理器接口
- Python可以使用函数和装饰器实现
- Python支持更灵活的链式调用
- Python的动态特性简化链的构建

关键理解：
责任链将请求沿着处理者链传递，Python的灵活性使链的构建更简单。
"""

from abc import ABC, abstractmethod
from typing import Any, Callable, Dict, List, Optional, Union, Tuple, Type
from dataclasses import dataclass, field
from enum import Enum, auto
from datetime import datetime, timedelta
import time
import json
import logging
import re
import hashlib
from functools import wraps
import threading
import asyncio
from pathlib import Path


# ============= 传统责任链模式 =============

class Handler(ABC):
    """
    处理器抽象基类 - 传统责任链模式
    
    定义处理请求的接口和链式调用机制
    
    Java对比：
    - Java使用abstract class定义Handler
    - Python使用ABC更灵活
    """
    
    def __init__(self):
        self._next_handler: Optional['Handler'] = None
    
    def set_next(self, handler: 'Handler') -> 'Handler':
        """设置下一个处理器"""
        self._next_handler = handler
        return handler  # 返回handler支持链式调用
    
    def handle(self, request: Any) -> Optional[Any]:
        """处理请求的模板方法"""
        # 尝试当前处理器处理
        result = self.do_handle(request)
        
        # 如果当前处理器无法处理，传递给下一个处理器
        if result is None and self._next_handler:
            return self._next_handler.handle(request)
        
        return result
    
    @abstractmethod
    def do_handle(self, request: Any) -> Optional[Any]:
        """具体的处理逻辑 - 子类实现"""
        pass
    
    def can_handle(self, request: Any) -> bool:
        """检查是否能处理请求 - 可选重写"""
        return True
    
    def get_handler_name(self) -> str:
        """获取处理器名称"""
        return self.__class__.__name__


# ============= 请求处理示例 =============

@dataclass
class Request:
    """
    请求对象
    
    包含请求的类型、数据和元信息
    """
    request_type: str
    data: Dict[str, Any]
    priority: int = 0
    timestamp: datetime = field(default_factory=datetime.now)
    user_id: Optional[str] = None
    session_id: Optional[str] = None
    metadata: Dict[str, Any] = field(default_factory=dict)
    
    def __post_init__(self):
        """初始化后处理"""
        if 'request_id' not in self.metadata:
            self.metadata['request_id'] = hashlib.md5(
                f"{self.timestamp}{self.request_type}{self.user_id}".encode()
            ).hexdigest()[:8]
    
    def get_request_id(self) -> str:
        """获取请求ID"""
        return self.metadata.get('request_id', 'unknown')
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            'request_type': self.request_type,
            'data': self.data,
            'priority': self.priority,
            'timestamp': self.timestamp.isoformat(),
            'user_id': self.user_id,
            'session_id': self.session_id,
            'metadata': self.metadata
        }


@dataclass
class Response:
    """
    响应对象
    
    包含处理结果和处理信息
    """
    success: bool
    data: Any = None
    message: str = ""
    handler_name: str = ""
    processing_time: float = 0.0
    error: Optional[str] = None
    metadata: Dict[str, Any] = field(default_factory=dict)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        return {
            'success': self.success,
            'data': self.data,
            'message': self.message,
            'handler_name': self.handler_name,
            'processing_time': self.processing_time,
            'error': self.error,
            'metadata': self.metadata
        }


# ============= 具体处理器实现 =============

class AuthenticationHandler(Handler):
    """
    身份验证处理器
    
    处理用户身份验证请求
    """
    
    def __init__(self, valid_users: List[str] = None):
        super().__init__()
        self.valid_users = valid_users or ['admin', 'user1', 'user2']
        self.failed_attempts: Dict[str, int] = {}
        self.max_attempts = 3
    
    def do_handle(self, request: Request) -> Optional[Response]:
        """处理身份验证"""
        if request.request_type != 'auth':
            return None
        
        start_time = time.time()
        
        try:
            username = request.data.get('username')
            password = request.data.get('password')
            
            if not username or not password:
                return Response(
                    success=False,
                    message="用户名和密码不能为空",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time,
                    error="missing_credentials"
                )
            
            # 检查失败次数
            if self.failed_attempts.get(username, 0) >= self.max_attempts:
                return Response(
                    success=False,
                    message=f"用户 {username} 已被锁定",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time,
                    error="account_locked"
                )
            
            # 简单的身份验证逻辑
            if username in self.valid_users and password == f"{username}_password":
                # 重置失败次数
                self.failed_attempts.pop(username, None)
                
                return Response(
                    success=True,
                    data={'user_id': username, 'role': 'user'},
                    message=f"用户 {username} 认证成功",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time,
                    metadata={'authenticated': True}
                )
            else:
                # 记录失败次数
                self.failed_attempts[username] = self.failed_attempts.get(username, 0) + 1
                
                return Response(
                    success=False,
                    message="用户名或密码错误",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time,
                    error="invalid_credentials"
                )
        
        except Exception as e:
            return Response(
                success=False,
                message="身份验证过程中发生错误",
                handler_name=self.get_handler_name(),
                processing_time=time.time() - start_time,
                error=str(e)
            )


class AuthorizationHandler(Handler):
    """
    授权处理器
    
    处理用户权限验证请求
    """
    
    def __init__(self):
        super().__init__()
        self.permissions = {
            'admin': ['read', 'write', 'delete', 'admin'],
            'user1': ['read', 'write'],
            'user2': ['read']
        }
    
    def do_handle(self, request: Request) -> Optional[Response]:
        """处理授权"""
        if request.request_type != 'authorize':
            return None
        
        start_time = time.time()
        
        try:
            user_id = request.data.get('user_id')
            required_permission = request.data.get('permission')
            resource = request.data.get('resource', 'default')
            
            if not user_id or not required_permission:
                return Response(
                    success=False,
                    message="用户ID和权限不能为空",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time,
                    error="missing_parameters"
                )
            
            user_permissions = self.permissions.get(user_id, [])
            
            if required_permission in user_permissions:
                return Response(
                    success=True,
                    data={
                        'user_id': user_id,
                        'permission': required_permission,
                        'resource': resource,
                        'granted': True
                    },
                    message=f"用户 {user_id} 具有 {required_permission} 权限",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time,
                    metadata={'authorized': True}
                )
            else:
                return Response(
                    success=False,
                    message=f"用户 {user_id} 没有 {required_permission} 权限",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time,
                    error="insufficient_permissions"
                )
        
        except Exception as e:
            return Response(
                success=False,
                message="授权过程中发生错误",
                handler_name=self.get_handler_name(),
                processing_time=time.time() - start_time,
                error=str(e)
            )


class ValidationHandler(Handler):
    """
    数据验证处理器
    
    处理数据验证请求
    """
    
    def __init__(self):
        super().__init__()
        self.validation_rules = {
            'email': r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$',
            'phone': r'^\+?1?\d{9,15}$',
            'username': r'^[a-zA-Z0-9_]{3,20}$'
        }
    
    def do_handle(self, request: Request) -> Optional[Response]:
        """处理数据验证"""
        if request.request_type != 'validate':
            return None
        
        start_time = time.time()
        
        try:
            data_to_validate = request.data.get('data', {})
            validation_type = request.data.get('type', 'general')
            
            validation_errors = []
            validated_data = {}
            
            if validation_type == 'user_registration':
                validation_errors, validated_data = self._validate_user_registration(data_to_validate)
            elif validation_type == 'contact_info':
                validation_errors, validated_data = self._validate_contact_info(data_to_validate)
            else:
                validation_errors, validated_data = self._validate_general(data_to_validate)
            
            if validation_errors:
                return Response(
                    success=False,
                    data={'errors': validation_errors},
                    message="数据验证失败",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time,
                    error="validation_failed"
                )
            else:
                return Response(
                    success=True,
                    data={'validated_data': validated_data},
                    message="数据验证成功",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time,
                    metadata={'validated': True}
                )
        
        except Exception as e:
            return Response(
                success=False,
                message="数据验证过程中发生错误",
                handler_name=self.get_handler_name(),
                processing_time=time.time() - start_time,
                error=str(e)
            )
    
    def _validate_user_registration(self, data: Dict[str, Any]) -> Tuple[List[str], Dict[str, Any]]:
        """验证用户注册数据"""
        errors = []
        validated = {}
        
        # 验证用户名
        username = data.get('username', '').strip()
        if not username:
            errors.append('用户名不能为空')
        elif not re.match(self.validation_rules['username'], username):
            errors.append('用户名格式不正确（3-20个字符，只能包含字母、数字和下划线）')
        else:
            validated['username'] = username
        
        # 验证邮箱
        email = data.get('email', '').strip()
        if not email:
            errors.append('邮箱不能为空')
        elif not re.match(self.validation_rules['email'], email):
            errors.append('邮箱格式不正确')
        else:
            validated['email'] = email.lower()
        
        # 验证密码
        password = data.get('password', '')
        if not password:
            errors.append('密码不能为空')
        elif len(password) < 6:
            errors.append('密码长度不能少于6位')
        else:
            validated['password'] = password
        
        return errors, validated
    
    def _validate_contact_info(self, data: Dict[str, Any]) -> Tuple[List[str], Dict[str, Any]]:
        """验证联系信息"""
        errors = []
        validated = {}
        
        # 验证邮箱（可选）
        email = data.get('email', '').strip()
        if email:
            if not re.match(self.validation_rules['email'], email):
                errors.append('邮箱格式不正确')
            else:
                validated['email'] = email.lower()
        
        # 验证电话（可选）
        phone = data.get('phone', '').strip()
        if phone:
            if not re.match(self.validation_rules['phone'], phone):
                errors.append('电话号码格式不正确')
            else:
                validated['phone'] = phone
        
        # 至少需要一种联系方式
        if not email and not phone:
            errors.append('至少需要提供邮箱或电话号码')
        
        return errors, validated
    
    def _validate_general(self, data: Dict[str, Any]) -> Tuple[List[str], Dict[str, Any]]:
        """通用验证"""
        errors = []
        validated = data.copy()
        
        # 检查必填字段
        required_fields = data.get('_required_fields', [])
        for field in required_fields:
            if field not in data or not data[field]:
                errors.append(f'字段 {field} 是必填的')
        
        return errors, validated


class LoggingHandler(Handler):
    """
    日志记录处理器
    
    处理日志记录请求
    """
    
    def __init__(self, log_level: str = 'INFO'):
        super().__init__()
        self.log_level = log_level.upper()
        self.logs: List[Dict[str, Any]] = []
    
    def do_handle(self, request: Request) -> Optional[Response]:
        """处理日志记录"""
        if request.request_type != 'log':
            return None
        
        start_time = time.time()
        
        try:
            level = request.data.get('level', 'INFO').upper()
            message = request.data.get('message', '')
            category = request.data.get('category', 'general')
            extra_data = request.data.get('extra', {})
            
            # 检查日志级别
            if not self._should_log(level):
                return Response(
                    success=True,
                    message=f"日志级别 {level} 被过滤",
                    handler_name=self.get_handler_name(),
                    processing_time=time.time() - start_time
                )
            
            # 创建日志条目
            log_entry = {
                'timestamp': datetime.now().isoformat(),
                'level': level,
                'message': message,
                'category': category,
                'user_id': request.user_id,
                'session_id': request.session_id,
                'request_id': request.get_request_id(),
                'extra': extra_data
            }
            
            # 存储日志
            self.logs.append(log_entry)
            
            # 输出日志
            print(f"[{log_entry['timestamp']}] {level} - {category}: {message}")
            
            return Response(
                success=True,
                data={'log_id': len(self.logs) - 1},
                message="日志记录成功",
                handler_name=self.get_handler_name(),
                processing_time=time.time() - start_time,
                metadata={'logged': True}
            )
        
        except Exception as e:
            return Response(
                success=False,
                message="日志记录过程中发生错误",
                handler_name=self.get_handler_name(),
                processing_time=time.time() - start_time,
                error=str(e)
            )
    
    def _should_log(self, level: str) -> bool:
        """检查是否应该记录日志"""
        level_priority = {
            'DEBUG': 0,
            'INFO': 1,
            'WARNING': 2,
            'ERROR': 3,
            'CRITICAL': 4
        }
        
        return level_priority.get(level, 1) >= level_priority.get(self.log_level, 1)
    
    def get_logs(self, category: Optional[str] = None, level: Optional[str] = None) -> List[Dict[str, Any]]:
        """获取日志"""
        filtered_logs = self.logs
        
        if category:
            filtered_logs = [log for log in filtered_logs if log['category'] == category]
        
        if level:
            filtered_logs = [log for log in filtered_logs if log['level'] == level.upper()]
        
        return filtered_logs


class DefaultHandler(Handler):
    """
    默认处理器
    
    处理所有未被其他处理器处理的请求
    """
    
    def do_handle(self, request: Request) -> Optional[Response]:
        """默认处理逻辑"""
        start_time = time.time()
        
        return Response(
            success=False,
            message=f"没有找到处理 '{request.request_type}' 类型请求的处理器",
            handler_name=self.get_handler_name(),
            processing_time=time.time() - start_time,
            error="no_handler_found",
            metadata={'unhandled_request': True}
        )


# ============= 函数式责任链 =============

def create_function_chain(*handlers: Callable[[Any], Optional[Any]]) -> Callable[[Any], Optional[Any]]:
    """
    函数式责任链 - Python特色实现
    
    使用函数组合创建责任链
    
    Python优势：
    - 函数作为一等公民
    - 更简洁的链式调用
    - 减少类的复杂性
    """
    
    def chain_handler(request: Any) -> Optional[Any]:
        """链式处理函数"""
        for handler in handlers:
            try:
                result = handler(request)
                if result is not None:
                    return result
            except Exception as e:
                print(f"处理器 {handler.__name__} 发生错误: {e}")
                continue
        
        return None
    
    return chain_handler


# 函数式处理器示例
def handle_math_operation(request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """处理数学运算"""
    if request.get('type') != 'math':
        return None
    
    operation = request.get('operation')
    a = request.get('a', 0)
    b = request.get('b', 0)
    
    try:
        if operation == 'add':
            result = a + b
        elif operation == 'subtract':
            result = a - b
        elif operation == 'multiply':
            result = a * b
        elif operation == 'divide':
            if b == 0:
                raise ValueError("除数不能为零")
            result = a / b
        else:
            return None
        
        return {
            'success': True,
            'result': result,
            'operation': f"{a} {operation} {b} = {result}",
            'handler': 'math_handler'
        }
    
    except Exception as e:
        return {
            'success': False,
            'error': str(e),
            'handler': 'math_handler'
        }


def handle_string_operation(request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """处理字符串操作"""
    if request.get('type') != 'string':
        return None
    
    operation = request.get('operation')
    text = request.get('text', '')
    
    try:
        if operation == 'uppercase':
            result = text.upper()
        elif operation == 'lowercase':
            result = text.lower()
        elif operation == 'reverse':
            result = text[::-1]
        elif operation == 'length':
            result = len(text)
        else:
            return None
        
        return {
            'success': True,
            'result': result,
            'operation': f"{operation}('{text}') = {result}",
            'handler': 'string_handler'
        }
    
    except Exception as e:
        return {
            'success': False,
            'error': str(e),
            'handler': 'string_handler'
        }


def handle_list_operation(request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """处理列表操作"""
    if request.get('type') != 'list':
        return None
    
    operation = request.get('operation')
    data = request.get('data', [])
    
    try:
        if operation == 'sum':
            result = sum(data)
        elif operation == 'max':
            result = max(data) if data else None
        elif operation == 'min':
            result = min(data) if data else None
        elif operation == 'sort':
            result = sorted(data)
        elif operation == 'reverse':
            result = list(reversed(data))
        else:
            return None
        
        return {
            'success': True,
            'result': result,
            'operation': f"{operation}({data}) = {result}",
            'handler': 'list_handler'
        }
    
    except Exception as e:
        return {
            'success': False,
            'error': str(e),
            'handler': 'list_handler'
        }


# ============= 装饰器责任链 =============

def chain_handler(handler_name: str):
    """
    责任链装饰器 - Python特色实现
    
    使用装饰器标记处理器函数
    """
    def decorator(func: Callable) -> Callable:
        func._handler_name = handler_name
        func._is_chain_handler = True
        return func
    return decorator


class DecoratorChain:
    """
    装饰器责任链管理器
    
    自动发现和管理装饰器标记的处理器
    """
    
    def __init__(self):
        self.handlers: List[Callable] = []
        self.handler_stats: Dict[str, Dict[str, Any]] = {}
    
    def register_handler(self, handler: Callable):
        """注册处理器"""
        if hasattr(handler, '_is_chain_handler'):
            self.handlers.append(handler)
            handler_name = getattr(handler, '_handler_name', handler.__name__)
            self.handler_stats[handler_name] = {
                'calls': 0,
                'successes': 0,
                'failures': 0,
                'total_time': 0.0
            }
            print(f"注册处理器: {handler_name}")
    
    def register_module_handlers(self, module):
        """注册模块中的所有处理器"""
        for name in dir(module):
            obj = getattr(module, name)
            if callable(obj) and hasattr(obj, '_is_chain_handler'):
                self.register_handler(obj)
    
    def handle_request(self, request: Any) -> Optional[Any]:
        """处理请求"""
        for handler in self.handlers:
            handler_name = getattr(handler, '_handler_name', handler.__name__)
            start_time = time.time()
            
            try:
                self.handler_stats[handler_name]['calls'] += 1
                
                result = handler(request)
                
                processing_time = time.time() - start_time
                self.handler_stats[handler_name]['total_time'] += processing_time
                
                if result is not None:
                    self.handler_stats[handler_name]['successes'] += 1
                    print(f"请求由 {handler_name} 处理")
                    return result
            
            except Exception as e:
                processing_time = time.time() - start_time
                self.handler_stats[handler_name]['total_time'] += processing_time
                self.handler_stats[handler_name]['failures'] += 1
                
                print(f"处理器 {handler_name} 发生错误: {e}")
                continue
        
        return None
    
    def get_stats(self) -> Dict[str, Dict[str, Any]]:
        """获取处理器统计信息"""
        stats = {}
        for name, data in self.handler_stats.items():
            avg_time = data['total_time'] / data['calls'] if data['calls'] > 0 else 0
            success_rate = data['successes'] / data['calls'] if data['calls'] > 0 else 0
            
            stats[name] = {
                'calls': data['calls'],
                'successes': data['successes'],
                'failures': data['failures'],
                'success_rate': f"{success_rate:.2%}",
                'avg_processing_time': f"{avg_time:.4f}s",
                'total_time': f"{data['total_time']:.4f}s"
            }
        
        return stats


# 装饰器处理器示例
@chain_handler('email_validator')
def validate_email_request(request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """验证邮箱请求"""
    if request.get('type') != 'validate_email':
        return None
    
    email = request.get('email', '')
    email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    
    is_valid = bool(re.match(email_pattern, email))
    
    return {
        'success': True,
        'valid': is_valid,
        'email': email,
        'message': '邮箱格式有效' if is_valid else '邮箱格式无效',
        'handler': 'email_validator'
    }


@chain_handler('password_validator')
def validate_password_request(request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """验证密码请求"""
    if request.get('type') != 'validate_password':
        return None
    
    password = request.get('password', '')
    
    # 密码强度检查
    checks = {
        'length': len(password) >= 8,
        'uppercase': bool(re.search(r'[A-Z]', password)),
        'lowercase': bool(re.search(r'[a-z]', password)),
        'digit': bool(re.search(r'\d', password)),
        'special': bool(re.search(r'[!@#$%^&*(),.?":{}|<>]', password))
    }
    
    score = sum(checks.values())
    strength = 'weak' if score < 3 else 'medium' if score < 5 else 'strong'
    
    return {
        'success': True,
        'strength': strength,
        'score': score,
        'checks': checks,
        'message': f'密码强度: {strength}',
        'handler': 'password_validator'
    }


@chain_handler('data_processor')
def process_data_request(request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
    """处理数据请求"""
    if request.get('type') != 'process_data':
        return None
    
    data = request.get('data', [])
    operation = request.get('operation', 'count')
    
    try:
        if operation == 'count':
            result = len(data)
        elif operation == 'unique':
            result = list(set(data))
        elif operation == 'filter_numbers':
            result = [x for x in data if isinstance(x, (int, float))]
        elif operation == 'filter_strings':
            result = [x for x in data if isinstance(x, str)]
        else:
            return None
        
        return {
            'success': True,
            'result': result,
            'operation': operation,
            'input_size': len(data),
            'handler': 'data_processor'
        }
    
    except Exception as e:
        return {
            'success': False,
            'error': str(e),
            'handler': 'data_processor'
        }


# ============= 异步责任链 =============

class AsyncHandler(ABC):
    """
    异步处理器抽象基类
    
    支持异步处理的责任链
    """
    
    def __init__(self):
        self._next_handler: Optional['AsyncHandler'] = None
    
    def set_next(self, handler: 'AsyncHandler') -> 'AsyncHandler':
        """设置下一个处理器"""
        self._next_handler = handler
        return handler
    
    async def handle(self, request: Any) -> Optional[Any]:
        """异步处理请求"""
        result = await self.do_handle(request)
        
        if result is None and self._next_handler:
            return await self._next_handler.handle(request)
        
        return result
    
    @abstractmethod
    async def do_handle(self, request: Any) -> Optional[Any]:
        """异步处理逻辑"""
        pass
    
    def get_handler_name(self) -> str:
        """获取处理器名称"""
        return self.__class__.__name__


class AsyncWebRequestHandler(AsyncHandler):
    """
    异步Web请求处理器
    
    模拟异步HTTP请求处理
    """
    
    def __init__(self, timeout: float = 5.0):
        super().__init__()
        self.timeout = timeout
    
    async def do_handle(self, request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """处理Web请求"""
        if request.get('type') != 'web_request':
            return None
        
        url = request.get('url', '')
        method = request.get('method', 'GET')
        
        try:
            # 模拟异步HTTP请求
            print(f"发起异步请求: {method} {url}")
            await asyncio.sleep(0.5)  # 模拟网络延迟
            
            # 模拟响应
            response_data = {
                'status_code': 200,
                'data': {'message': 'Success', 'timestamp': datetime.now().isoformat()},
                'headers': {'Content-Type': 'application/json'}
            }
            
            return {
                'success': True,
                'response': response_data,
                'url': url,
                'method': method,
                'handler': self.get_handler_name()
            }
        
        except asyncio.TimeoutError:
            return {
                'success': False,
                'error': 'Request timeout',
                'url': url,
                'handler': self.get_handler_name()
            }
        except Exception as e:
            return {
                'success': False,
                'error': str(e),
                'url': url,
                'handler': self.get_handler_name()
            }


class AsyncDatabaseHandler(AsyncHandler):
    """
    异步数据库处理器
    
    模拟异步数据库操作
    """
    
    def __init__(self):
        super().__init__()
        self.data_store: Dict[str, Any] = {}
    
    async def do_handle(self, request: Dict[str, Any]) -> Optional[Dict[str, Any]]:
        """处理数据库请求"""
        if request.get('type') != 'database':
            return None
        
        operation = request.get('operation')
        table = request.get('table', 'default')
        
        try:
            # 模拟数据库延迟
            await asyncio.sleep(0.2)
            
            if operation == 'create':
                data = request.get('data', {})
                record_id = f"{table}_{len(self.data_store)}"
                self.data_store[record_id] = data
                
                return {
                    'success': True,
                    'operation': 'create',
                    'record_id': record_id,
                    'data': data,
                    'handler': self.get_handler_name()
                }
            
            elif operation == 'read':
                record_id = request.get('record_id')
                if record_id in self.data_store:
                    return {
                        'success': True,
                        'operation': 'read',
                        'record_id': record_id,
                        'data': self.data_store[record_id],
                        'handler': self.get_handler_name()
                    }
                else:
                    return {
                        'success': False,
                        'error': 'Record not found',
                        'record_id': record_id,
                        'handler': self.get_handler_name()
                    }
            
            elif operation == 'list':
                table_records = {k: v for k, v in self.data_store.items() if k.startswith(f"{table}_")}
                return {
                    'success': True,
                    'operation': 'list',
                    'table': table,
                    'records': table_records,
                    'count': len(table_records),
                    'handler': self.get_handler_name()
                }
            
            else:
                return None
        
        except Exception as e:
            return {
                'success': False,
                'error': str(e),
                'operation': operation,
                'handler': self.get_handler_name()
            }


# ============= 中间件模式 =============

class Middleware(ABC):
    """
    中间件抽象基类
    
    类似于责任链，但每个中间件都会被执行
    """
    
    @abstractmethod
    async def process(self, request: Any, next_middleware: Callable) -> Any:
        """处理请求并调用下一个中间件"""
        pass


class MiddlewareChain:
    """
    中间件链管理器
    
    按顺序执行所有中间件
    """
    
    def __init__(self):
        self.middlewares: List[Middleware] = []
    
    def add_middleware(self, middleware: Middleware):
        """添加中间件"""
        self.middlewares.append(middleware)
    
    async def execute(self, request: Any, final_handler: Callable) -> Any:
        """执行中间件链"""
        async def create_next(index: int):
            if index >= len(self.middlewares):
                return await final_handler(request)
            
            middleware = self.middlewares[index]
            
            async def next_func():
                return await create_next(index + 1)
            
            return await middleware.process(request, next_func)
        
        return await create_next(0)


class LoggingMiddleware(Middleware):
    """
    日志中间件
    
    记录请求和响应信息
    """
    
    async def process(self, request: Any, next_middleware: Callable) -> Any:
        """处理日志记录"""
        start_time = time.time()
        request_id = getattr(request, 'get_request_id', lambda: 'unknown')()
        
        print(f"[{datetime.now().isoformat()}] 请求开始: {request_id}")
        
        try:
            result = await next_middleware()
            
            processing_time = time.time() - start_time
            print(f"[{datetime.now().isoformat()}] 请求完成: {request_id}, 耗时: {processing_time:.4f}s")
            
            return result
        
        except Exception as e:
            processing_time = time.time() - start_time
            print(f"[{datetime.now().isoformat()}] 请求失败: {request_id}, 错误: {e}, 耗时: {processing_time:.4f}s")
            raise


class AuthenticationMiddleware(Middleware):
    """
    身份验证中间件
    
    验证请求的身份信息
    """
    
    def __init__(self, required_auth: bool = True):
        self.required_auth = required_auth
    
    async def process(self, request: Any, next_middleware: Callable) -> Any:
        """处理身份验证"""
        if self.required_auth:
            user_id = getattr(request, 'user_id', None)
            if not user_id:
                raise PermissionError("需要身份验证")
            
            print(f"身份验证通过: {user_id}")
        
        return await next_middleware()


class RateLimitMiddleware(Middleware):
    """
    限流中间件
    
    限制请求频率
    """
    
    def __init__(self, max_requests: int = 10, time_window: int = 60):
        self.max_requests = max_requests
        self.time_window = time_window
        self.request_counts: Dict[str, List[float]] = {}
    
    async def process(self, request: Any, next_middleware: Callable) -> Any:
        """处理限流"""
        user_id = getattr(request, 'user_id', 'anonymous')
        current_time = time.time()
        
        # 清理过期的请求记录
        if user_id in self.request_counts:
            self.request_counts[user_id] = [
                req_time for req_time in self.request_counts[user_id]
                if current_time - req_time < self.time_window
            ]
        else:
            self.request_counts[user_id] = []
        
        # 检查请求频率
        if len(self.request_counts[user_id]) >= self.max_requests:
            raise Exception(f"请求频率超限: {user_id}")
        
        # 记录当前请求
        self.request_counts[user_id].append(current_time)
        
        print(f"限流检查通过: {user_id} ({len(self.request_counts[user_id])}/{self.max_requests})")
        
        return await next_middleware()


# ============= 演示函数 =============

def demonstrate_traditional_chain():
    """
    演示传统责任链模式
    
    概述引导：
    展示传统责任链模式的实现，包括处理器接口、具体处理器
    和链式调用机制。
    
    学习要点：
    1. 处理器接口的定义
    2. 具体处理器的实现
    3. 链式调用的构建
    4. 请求的传递机制
    
    关键理解：
    责任链将请求沿着处理者链传递，直到找到能处理的处理器。
    """
    print("=== 传统责任链模式演示 ===")
    print("\n学习目标：")
    print("- 理解责任链的结构")
    print("- 掌握处理器的链式调用")
    print("- 学习请求的传递机制")
    print("\n重点概念：")
    print("- 处理器链")
    print("- 请求传递")
    print("- 解耦发送者和接收者")
    print("=" * 50)
    
    # 创建处理器链
    auth_handler = AuthenticationHandler()
    authz_handler = AuthorizationHandler()
    validation_handler = ValidationHandler()
    logging_handler = LoggingHandler()
    default_handler = DefaultHandler()
    
    # 构建责任链
    auth_handler.set_next(authz_handler).set_next(validation_handler).set_next(logging_handler).set_next(default_handler)
    
    # 测试身份验证请求
    print("\n=== 身份验证测试 ===")
    
    # 成功的身份验证
    auth_request = Request(
        request_type='auth',
        data={'username': 'admin', 'password': 'admin_password'},
        user_id='system'
    )
    
    response = auth_handler.handle(auth_request)
    print(f"认证结果: {response.to_dict()}")
    
    # 失败的身份验证
    failed_auth_request = Request(
        request_type='auth',
        data={'username': 'admin', 'password': 'wrong_password'},
        user_id='system'
    )
    
    response = auth_handler.handle(failed_auth_request)
    print(f"\n认证失败结果: {response.to_dict()}")
    
    # 测试授权请求
    print("\n=== 授权测试 ===")
    
    authz_request = Request(
        request_type='authorize',
        data={'user_id': 'admin', 'permission': 'write', 'resource': 'users'},
        user_id='admin'
    )
    
    response = auth_handler.handle(authz_request)
    print(f"授权结果: {response.to_dict()}")
    
    # 测试数据验证请求
    print("\n=== 数据验证测试 ===")
    
    validation_request = Request(
        request_type='validate',
        data={
            'type': 'user_registration',
            'data': {
                'username': 'newuser',
                'email': 'newuser@example.com',
                'password': 'password123'
            }
        },
        user_id='system'
    )
    
    response = auth_handler.handle(validation_request)
    print(f"验证结果: {response.to_dict()}")
    
    # 测试日志记录请求
    print("\n=== 日志记录测试 ===")
    
    log_request = Request(
        request_type='log',
        data={
            'level': 'INFO',
            'message': '用户登录成功',
            'category': 'security',
            'extra': {'ip': '192.168.1.1'}
        },
        user_id='admin'
    )
    
    response = auth_handler.handle(log_request)
    print(f"日志结果: {response.to_dict()}")
    
    # 测试未知请求类型
    print("\n=== 未知请求测试 ===")
    
    unknown_request = Request(
        request_type='unknown',
        data={'test': 'data'},
        user_id='admin'
    )
    
    response = auth_handler.handle(unknown_request)
    print(f"未知请求结果: {response.to_dict()}")


def demonstrate_functional_chain():
    """
    演示函数式责任链
    """
    print("\n=== 函数式责任链演示 ===")
    
    # 创建函数式责任链
    operation_chain = create_function_chain(
        handle_math_operation,
        handle_string_operation,
        handle_list_operation
    )
    
    # 测试数学运算
    print("\n数学运算测试:")
    math_requests = [
        {'type': 'math', 'operation': 'add', 'a': 10, 'b': 5},
        {'type': 'math', 'operation': 'divide', 'a': 10, 'b': 3},
        {'type': 'math', 'operation': 'divide', 'a': 10, 'b': 0}  # 除零错误
    ]
    
    for request in math_requests:
        result = operation_chain(request)
        print(f"请求: {request}")
        print(f"结果: {result}\n")
    
    # 测试字符串操作
    print("字符串操作测试:")
    string_requests = [
        {'type': 'string', 'operation': 'uppercase', 'text': 'hello world'},
        {'type': 'string', 'operation': 'reverse', 'text': 'python'},
        {'type': 'string', 'operation': 'length', 'text': 'responsibility chain'}
    ]
    
    for request in string_requests:
        result = operation_chain(request)
        print(f"请求: {request}")
        print(f"结果: {result}\n")
    
    # 测试列表操作
    print("列表操作测试:")
    list_requests = [
        {'type': 'list', 'operation': 'sum', 'data': [1, 2, 3, 4, 5]},
        {'type': 'list', 'operation': 'sort', 'data': [5, 2, 8, 1, 9]},
        {'type': 'list', 'operation': 'max', 'data': [3, 7, 2, 9, 1]}
    ]
    
    for request in list_requests:
        result = operation_chain(request)
        print(f"请求: {request}")
        print(f"结果: {result}\n")
    
    # 测试未知类型
    print("未知类型测试:")
    unknown_request = {'type': 'unknown', 'data': 'test'}
    result = operation_chain(unknown_request)
    print(f"请求: {unknown_request}")
    print(f"结果: {result}")


def demonstrate_decorator_chain():
    """
    演示装饰器责任链
    """
    print("\n=== 装饰器责任链演示 ===")
    
    # 创建装饰器链管理器
    chain = DecoratorChain()
    
    # 注册处理器
    chain.register_handler(validate_email_request)
    chain.register_handler(validate_password_request)
    chain.register_handler(process_data_request)
    
    # 测试邮箱验证
    print("\n邮箱验证测试:")
    email_requests = [
        {'type': 'validate_email', 'email': 'user@example.com'},
        {'type': 'validate_email', 'email': 'invalid-email'},
        {'type': 'validate_email', 'email': 'test@domain.co.uk'}
    ]
    
    for request in email_requests:
        result = chain.handle_request(request)
        print(f"请求: {request}")
        print(f"结果: {result}\n")
    
    # 测试密码验证
    print("密码验证测试:")
    password_requests = [
        {'type': 'validate_password', 'password': 'weak'},
        {'type': 'validate_password', 'password': 'Medium123'},
        {'type': 'validate_password', 'password': 'Strong123!@#'}
    ]
    
    for request in password_requests:
        result = chain.handle_request(request)
        print(f"请求: {request}")
        print(f"结果: {result}\n")
    
    # 测试数据处理
    print("数据处理测试:")
    data_requests = [
        {'type': 'process_data', 'operation': 'count', 'data': [1, 2, 3, 4, 5]},
        {'type': 'process_data', 'operation': 'unique', 'data': [1, 2, 2, 3, 3, 4]},
        {'type': 'process_data', 'operation': 'filter_numbers', 'data': [1, 'a', 2, 'b', 3.14]}
    ]
    
    for request in data_requests:
        result = chain.handle_request(request)
        print(f"请求: {request}")
        print(f"结果: {result}\n")
    
    # 显示统计信息
    print("处理器统计信息:")
    stats = chain.get_stats()
    for handler_name, handler_stats in stats.items():
        print(f"{handler_name}: {handler_stats}")


async def demonstrate_async_chain():
    """
    演示异步责任链
    """
    print("\n=== 异步责任链演示 ===")
    
    # 创建异步处理器链
    web_handler = AsyncWebRequestHandler()
    db_handler = AsyncDatabaseHandler()
    
    web_handler.set_next(db_handler)
    
    # 测试Web请求
    print("\nWeb请求测试:")
    web_requests = [
        {'type': 'web_request', 'url': 'https://api.example.com/users', 'method': 'GET'},
        {'type': 'web_request', 'url': 'https://api.example.com/posts', 'method': 'POST'}
    ]
    
    for request in web_requests:
        result = await web_handler.handle(request)
        print(f"请求: {request}")
        print(f"结果: {result}\n")
    
    # 测试数据库操作
    print("数据库操作测试:")
    db_requests = [
        {
            'type': 'database',
            'operation': 'create',
            'table': 'users',
            'data': {'name': 'Alice', 'email': 'alice@example.com'}
        },
        {
            'type': 'database',
            'operation': 'create',
            'table': 'users',
            'data': {'name': 'Bob', 'email': 'bob@example.com'}
        },
        {
            'type': 'database',
            'operation': 'list',
            'table': 'users'
        },
        {
            'type': 'database',
            'operation': 'read',
            'record_id': 'users_0'
        }
    ]
    
    for request in db_requests:
        result = await web_handler.handle(request)
        print(f"请求: {request}")
        print(f"结果: {result}\n")


async def demonstrate_middleware_pattern():
    """
    演示中间件模式
    """
    print("\n=== 中间件模式演示 ===")
    
    # 创建中间件链
    middleware_chain = MiddlewareChain()
    
    # 添加中间件
    middleware_chain.add_middleware(LoggingMiddleware())
    middleware_chain.add_middleware(AuthenticationMiddleware(required_auth=True))
    middleware_chain.add_middleware(RateLimitMiddleware(max_requests=5, time_window=60))
    
    # 定义最终处理器
    async def final_handler(request):
        await asyncio.sleep(0.1)  # 模拟处理时间
        return {
            'success': True,
            'message': '请求处理成功',
            'data': request.data if hasattr(request, 'data') else {}
        }
    
    # 测试正常请求
    print("\n正常请求测试:")
    normal_request = Request(
        request_type='api_call',
        data={'action': 'get_user_info'},
        user_id='user123'
    )
    
    try:
        result = await middleware_chain.execute(normal_request, final_handler)
        print(f"处理结果: {result}\n")
    except Exception as e:
        print(f"处理失败: {e}\n")
    
    # 测试未认证请求
    print("未认证请求测试:")
    unauth_request = Request(
        request_type='api_call',
        data={'action': 'get_user_info'},
        user_id=None  # 没有用户ID
    )
    
    try:
        result = await middleware_chain.execute(unauth_request, final_handler)
        print(f"处理结果: {result}\n")
    except Exception as e:
        print(f"处理失败: {e}\n")
    
    # 测试频率限制
    print("频率限制测试:")
    rate_limit_request = Request(
        request_type='api_call',
        data={'action': 'bulk_operation'},
        user_id='user123'
    )
    
    # 连续发送多个请求测试限流
    for i in range(7):  # 超过限制的5个请求
        try:
            result = await middleware_chain.execute(rate_limit_request, final_handler)
            print(f"请求 {i+1} 成功: {result.get('message', 'Unknown')}")
        except Exception as e:
            print(f"请求 {i+1} 失败: {e}")


def demonstrate_performance_comparison():
    """
    演示性能对比
    """
    print("\n=== 性能对比演示 ===")
    
    # 传统责任链性能测试
    print("\n传统责任链性能测试:")
    
    auth_handler = AuthenticationHandler()
    authz_handler = AuthorizationHandler()
    validation_handler = ValidationHandler()
    logging_handler = LoggingHandler()
    default_handler = DefaultHandler()
    
    auth_handler.set_next(authz_handler).set_next(validation_handler).set_next(logging_handler).set_next(default_handler)
    
    # 测试1000次请求
    start_time = time.time()
    for i in range(1000):
        request = Request(
            request_type='auth',
            data={'username': 'user1', 'password': 'user1_password'},
            user_id='system'
        )
        auth_handler.handle(request)
    
    traditional_time = time.time() - start_time
    print(f"传统责任链处理1000次请求耗时: {traditional_time:.4f}秒")
    
    # 函数式责任链性能测试
    print("\n函数式责任链性能测试:")
    
    operation_chain = create_function_chain(
        handle_math_operation,
        handle_string_operation,
        handle_list_operation
    )
    
    start_time = time.time()
    for i in range(1000):
        request = {'type': 'math', 'operation': 'add', 'a': i, 'b': i+1}
        operation_chain(request)
    
    functional_time = time.time() - start_time
    print(f"函数式责任链处理1000次请求耗时: {functional_time:.4f}秒")
    
    # 装饰器责任链性能测试
    print("\n装饰器责任链性能测试:")
    
    chain = DecoratorChain()
    chain.register_handler(validate_email_request)
    chain.register_handler(validate_password_request)
    chain.register_handler(process_data_request)
    
    start_time = time.time()
    for i in range(1000):
        request = {'type': 'validate_email', 'email': f'user{i}@example.com'}
        chain.handle_request(request)
    
    decorator_time = time.time() - start_time
    print(f"装饰器责任链处理1000次请求耗时: {decorator_time:.4f}秒")
    
    # 性能对比总结
    print("\n=== 性能对比总结 ===")
    print(f"传统责任链: {traditional_time:.4f}秒")
    print(f"函数式责任链: {functional_time:.4f}秒 (相对性能: {functional_time/traditional_time:.2f}x)")
    print(f"装饰器责任链: {decorator_time:.4f}秒 (相对性能: {decorator_time/traditional_time:.2f}x)")
    
    # 内存使用对比
    print("\n=== 内存使用特点 ===")
    print("传统责任链:")
    print("- 每个处理器都是独立的对象")
    print("- 需要维护链式引用")
    print("- 内存开销相对较大")
    
    print("\n函数式责任链:")
    print("- 使用函数而非对象")
    print("- 内存开销较小")
    print("- 更适合简单的处理逻辑")
    
    print("\n装饰器责任链:")
    print("- 结合了对象和函数的优势")
    print("- 支持动态注册")
    print("- 提供统计功能")


def demonstrate_java_comparison():
    """
    演示与Java的对比
    """
    print("\n=== Python vs Java 责任链模式对比 ===")
    
    print("\n=== Java实现特点 ===")
    print("""
    Java责任链模式通常的实现:
    
    // 抽象处理器
    abstract class Handler {
        protected Handler nextHandler;
        
        public void setNext(Handler handler) {
            this.nextHandler = handler;
        }
        
        public abstract void handleRequest(Request request);
    }
    
    // 具体处理器
    class ConcreteHandler extends Handler {
        @Override
        public void handleRequest(Request request) {
            if (canHandle(request)) {
                // 处理请求
            } else if (nextHandler != null) {
                nextHandler.handleRequest(request);
            }
        }
    }
    
    Java特点:
    - 使用抽象类定义处理器接口
    - 需要显式的继承关系
    - 类型安全但灵活性较低
    - 需要更多的样板代码
    """)
    
    print("\n=== Python实现优势 ===")
    print("""
    Python责任链模式的优势:
    
    1. 多种实现方式:
       - 传统OOP方式（类似Java）
       - 函数式方式（利用函数是一等公民）
       - 装饰器方式（Python特色）
       - 异步方式（支持async/await）
    
    2. 动态特性:
       - 运行时动态添加/移除处理器
       - 动态修改处理逻辑
       - 支持鸭子类型
    
    3. 简洁性:
       - 更少的样板代码
       - 更直观的链式调用
       - 支持链式构建（method chaining）
    
    4. 灵活性:
       - 可以混合使用不同类型的处理器
       - 支持函数和对象的混合使用
       - 更容易进行单元测试
    """)
    
    print("\n=== 使用场景对比 ===")
    print("""
    Java适用场景:
    - 大型企业应用
    - 需要严格类型检查的场景
    - 团队开发需要明确接口契约
    
    Python适用场景:
    - 快速原型开发
    - 需要灵活处理逻辑的场景
    - 数据处理管道
    - Web框架中间件
    - 异步处理场景
    """)


def main():
    """
    主函数 - 演示所有责任链模式实现
    """
    print("Python责任链模式完整演示")
    print("=" * 60)
    
    # 传统责任链演示
    demonstrate_traditional_chain()
    
    # 函数式责任链演示
    demonstrate_functional_chain()
    
    # 装饰器责任链演示
    demonstrate_decorator_chain()
    
    # 异步责任链演示
    print("\n开始异步演示...")
    asyncio.run(demonstrate_async_chain())
    
    # 中间件模式演示
    print("\n开始中间件演示...")
    asyncio.run(demonstrate_middleware_pattern())
    
    # 性能对比演示
    demonstrate_performance_comparison()
    
    # Java对比演示
    demonstrate_java_comparison()
    
    print("\n=== 总结 ===")
    print("""
    责任链模式的Python实现要点:
    
    1. 传统方式：适合复杂的业务逻辑
    2. 函数式方式：适合简单的处理流程
    3. 装饰器方式：适合需要统计和管理的场景
    4. 异步方式：适合I/O密集型操作
    5. 中间件模式：适合Web应用和请求处理
    
    选择建议:
    - 简单处理：使用函数式
    - 复杂业务：使用传统OOP
    - 需要统计：使用装饰器
    - 异步处理：使用async/await
    - Web应用：使用中间件模式
    """)


if __name__ == "__main__":
    main()